<?php

class Rrd_Graph {
	private static $color = array("#0000FF", "#00FF00", "#FF0000", "#FFFF00", "#00FFFF", "#FF00FF");
	private static $path = "./img/";
	private $params = array("width"=> "918", "height"=>"225", "vertical-label"=>"Degreas", "color"=>array("BACK#FFFFFF", "SHADEA#FFFFFF", "SHADEB#FFFFFF", "CANVAS#FFFFFF"), "alt-autoscale"=>true, "disable-rrdtool-tag"=>true, "slope-mode"=>true);
	private $databases = array();

	public static function setPath($path) {
		Rrd_Graph::$path = $path;
	}

	private function createGraph($type) {
		$file = Rrd_Graph::$path . "/graph_" . $type . ".png";
		$params = $this->params;
		$params["start"] = "-1" . $type; // "-1d";
		$params["imgformat"] = "PNG";
		$params["watermark"] = date("Y-m-d H:i:s");
		$cmd = sprintf("/usr/bin/rrdtool graph %s ", $file);
		foreach($params as $pKey=>$pValue) {
			if(is_array($pValue)) {
				foreach($pValue as $value) {
					$cmd .= sprintf("--%s=%s ", $pKey, $value);
				}
			} elseif(is_bool($pValue)) {
				if($pValue) {
					$cmd .= sprintf("--%s ", $pKey);
				}
			} else {
				$cmd .= sprintf("--%s=\"%s\" ", $pKey, $pValue);
			}
		}
		$i = 0;
		foreach($this->databases as $database) {
			$cmd .= " " . $database->getGraphCommand(Rrd_Graph::$color[$i++]);
		}
		Util_Shell::exec($cmd, array(Log_Logger::get(), "debug"));
	}

	public function setParams($values) {
		foreach($values as $key => $value) {
			$this->setParam($key, $value);
		}
	}

	public function setParam($key, $value) {
		$this->params[$key] = $value;
	}

	public function addDatabase($db) {
		$this->databases[] = $db;
	}

	public function createDay() {
		$this->createGraph("d");
	}

	public function createWeek() {
		$this->createGraph("w");
	}

	public function createMonth() {
		$this->createGraph("m");
	}

	public function createYear() {
		$this->createGraph("y");
	}

	public function createAll() {
		$this->createDay();
		$this->createWeek();
		$this->createMonth();
		$this->createYear();
	}
}

?>
